<template>
	<div id="multi-tag-input" class="form-group has-warning">
		<div class="tag-list">
			<span class="tag-list-item" v-for="item in subdata" :key="item">
				{{item}}
				<a @click="deleteDataByKey(item)"><icon class="fa-times p-l-5"></icon></a>
			</span>
		</div>
		<input type="text" class="form-control" v-bind:style="{'padding-left': paddingLeft + 'px'}"
			   @keyup.enter="submit" @keydown.delete="deleteData"/>
	</div>
</template>

<script>
	/* eslint-disable no-undef */

	import './tag.css';
	import Icon from '../widget/Icon.vue';
	import Notify from '../../plugins/Notify';
	export default {
		name: 'MultiTagInput',
		props: {
			data: {type: Array, default: () => { return []; }},
			max: {type: Number, default: -1}
		},
		data () {
			return {
				subdata: [],
				paddingLeft: 0
			};
		},
		methods: {
			computePaddingLeft (maxLength) {
				let tagList = $(this.$el);
				let maxWidth = tagList.width();
				let items = $('.tag-list > span');
				let lineWidth = 0;
				if (items.length === 0) {
					this.paddingLeft = 0;
				} else {
					for (let i = 0; i < maxLength; i++) {
						lineWidth += $(items[i]).width() + 25;
						if (lineWidth > maxWidth) {
							lineWidth = $(items[i]).width() + 25;
						}
					}
					if (lineWidth + 50 >= maxWidth) {
						tagList.css({height: tagList.height() + 31.2 + 'px'});
						this.paddingLeft = 0;
					} else {
						tagList.css({height: 'auto'});
						this.paddingLeft = lineWidth + 10;
					}
				}
			},
			submit (event) {
				if (event.srcElement.value === '') {
					$().animate()
					return;
				}
				if (this.max && this.max <= this.subdata.length) {
					Notify.open({fixed: 'top-center', type: 'danger', content: '无法添加了 已达到最大限制'});
					return;
				}

				this.addData(event.srcElement.value);
				event.srcElement.value = '';
			},
			deleteData () {
				if (event.srcElement.value !== '') {
					return;
				}
				if (this.subdata && this.subdata.length) {
					this.subdata.pop();
				}
			},
			addData (key) {
				if (jQuery.inArray(key, this.subdata) !== -1) {
					Notify.open({fixed: 'top-center', type: 'danger', content: `${key}已经存在`});
					return;
				}
				this.subdata.push(key);
			},
			deleteDataByKey (key) {
				if ($.inArray(key, this.subdata) !== -1) {
					this.subdata.splice($.inArray(key, this.subdata), 1);
				}
			}
		},
		watch: {
			subdata: function (newVal) {
				this.$emit('input', newVal);
				this.$nextTick(() => {
					this.computePaddingLeft(newVal.length);
				});
			},
			data: function (newVal) {
				this.subdata = newVal;
			}
		},
		components: {
			Icon
		},
		mounted () {
			this.subdata = this.data;
			this.computePaddingLeft(this.subdata.length);
		}
	};
</script>
